import NProgress from "nprogress";
import UrlNS from "@/api/UrlDefine";
import NetworkUtil from "@/utils/NetworkUtil";
import { UserStoreModule } from "@/store/modules/UserStore";
import router from "@/router";
import { toHump } from "./utils";
import LayoutView from "@/layouts/LayoutView.vue";
import { LayoutStoreModule } from "@/store/modules/LayoutStore";
import Cookies from "js-cookie";
import { routes as constantRoutes } from "@/router";
import { RouteConfig } from "vue-router";

export function loadAllRouters() {
  const promise = new Promise<RouteConfig[]>((resolve, reject) => {
    NetworkUtil.postReq(UrlNS.getMenuListByRoleId, {
      userId: UserStoreModule.userId,
      roleId: UserStoreModule.roleId,
    })
      .then((resp) => {
        console.log("routets:", resp.data);
        if (resp.data.code == 200) {
          const routes = generatorRoutes(resp.data.data);
          resolve(routes);
        } else {
          reject(new Error(resp.data.msg));
        }

        // LayoutStoreModule.initPermissionRoute(routes);
      })
      .catch((err: Error) => {
        console.log(err);
        reject(err);
      });
  });
  return promise;
}

function getComponent(it) {
  return (resolve) => {
    if (it.children && it.children.length > 0) {
      require(["@/layouts/components/LyRouterViewLayout.vue"], resolve);
    } else {
      require(["@/views" + it.menuUrl], resolve);
    }
  };
}

function getCharCount(str, char) {
  let regex = new RegExp(char, "g");
  let result = str.match(regex);
  let count = !result ? 0 : result.length;
  return count;
}

function isMenu(path) {
  return getCharCount(path, "/") === 1;
}

function getNameByUrl(menuUrl) {
  const temp = menuUrl.split("/");
  return toHump(temp[temp.length - 1]);
}
function generatorRoutes(res) {
  const tempRoutes: any = [];
  res.forEach((it) => {
    const route = {
      path: it.menuUrl,
      name: getNameByUrl(it.menuUrl),
      hidden: !!it.hidden,
      component: isMenu(it.menuUrl) ? LayoutView : getComponent(it),
      meta: {
        title: it.menuName,
        affix: !!it.affix,
        cacheable: !!it.cacheable,
        icon: it.icon || "",
        tip: it.tip,
      },
    };
    if (it.children) {
      route["children"] = generatorRoutes(it.children);
    }
    tempRoutes.push(route);
  });
  return tempRoutes;
}
function isTokenExpired() {
  if (!UserStoreModule.userId || !UserStoreModule.roleId) {
    return false;
  }
  const token = Cookies.get("admin-token");
  return !!token;
}
const whiteList = ["login"];

router.beforeEach((to, from, next) => {
  NProgress.start();

  if (whiteList.includes(to.name!)) {
    next();
    NProgress.done();
  } else {
    if (!isTokenExpired()) {
      next(`/login?redirect=${to.path}`);
      NProgress.done();
    } else {
      const isEmptyRoute = LayoutStoreModule.isEmptyPermissionRoute;
      if (isEmptyRoute) {
        // 加载路由
        const accessRoutes: any[] = [];
        loadAllRouters().then(async (routes) => {
          accessRoutes.push(...routes);
          accessRoutes.push({
            path: "*",
            redirect: "/404",
            hidden: true,
          });
          LayoutStoreModule.initPermissionRoute([
            ...constantRoutes,
            ...accessRoutes,
          ]);
          router.addRoutes(accessRoutes);
          // @ts-ignore
          next({ ...to, replace: true });
        });
      } else {
        next();
      }
    }
  }
});

router.afterEach((to, from) => {
  NProgress.done();
});
